package BLC

import (
	"bytes"
	"crypto/ecdsa"
	"encoding/hex"
)

func (bc *BlockChain)Signature(tx *Transaction,privateKey ecdsa.PrivateKey){

	var prevTXs=make(map[string]Transaction)

	for _,in:=range tx.Vin{
		prevTX:=bc.FindTransaction(in.Txid)
		prevTXs[hex.EncodeToString(in.Txid)]=prevTX
	}

	tx.Sign(privateKey,prevTXs)

}

func (bc *BlockChain)FindTransaction(ID []byte)Transaction{

	bci:=bc.NewIterator()
	var block *Block

	for {
		block,bci=bci.Next()
		if bci==nil{
			break
		}
		for _,tx:=range block.Transactions{
				if bytes.Compare(tx.ID,ID)==0{
					return *tx
				}
		}
	}
	return Transaction{}
}

func (bc *BlockChain)VerifySignature(tx *Transaction)bool{
		prevTXs:=make(map[string]Transaction)
		for _,vin:=range tx.Vin{
			transaction:=bc.FindTransaction(vin.Txid)
			prevTXs[hex.EncodeToString(vin.Txid)]=transaction
		}
		return tx.VerifySignature(prevTXs)
}
